package com.yu.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yu.crm.domain.pojo.CrmRole;
import com.yu.crm.mapper.CrmRoleMapper;
import com.yu.crm.service.CrmRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yxzz.common.config.UserCacheManager;
import com.yxzz.common.helper.DataHelpers;
import com.yxzz.common.helper.DateHelpers;
import com.yxzz.common.helper.ExceptionHelpers;
import com.yxzz.common.helper.valid.ValidatorHelpers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author donnie-bin
 * @since 2019-06-10
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class CrmRoleServiceImpl extends ServiceImpl<CrmRoleMapper, CrmRole> implements CrmRoleService {

    @Autowired
    UserCacheManager userCacheManager;

    @Override
    public boolean saveOrUpdate(CrmRole entity) {
        if(DataHelpers.isEmpty(entity.getId())){
            QueryWrapper<CrmRole> queryWrapper =new QueryWrapper<>();
            queryWrapper.eq("role_group_id", entity.getRoleGroupId());
            queryWrapper.eq("role_name", entity.getRoleName());
            int oldCount = super.count(queryWrapper);
            ValidatorHelpers.validateDataExist("角色名称不能重复", oldCount);
            entity.setGmtCreate(DateHelpers.now());
            entity.setGmtModified(DateHelpers.now());
            return ExceptionHelpers.checkData(super.save(entity), "新增失败");
        }else{
            entity.setGmtModified(DateHelpers.now());
            return ExceptionHelpers.checkData(super.updateById(entity), "更新失败");
        }
    }

    @Override
    public boolean removeById(Serializable id) {
        return ExceptionHelpers.checkData(super.removeById(id), "删除失败");
    }

    @Override
    public List<CrmRole> getListByUserId() {
        String userId = userCacheManager.getCurrentUser().getUserId();
//        String userId = "admin";
        return  baseMapper.getListByUserId(userId);
    }

    @Override
    public IPage<CrmRole> list(IPage<CrmRole> page, CrmRole queryInfo) {
        List<Integer> roleTypes=new ArrayList<>();
        roleTypes.add(1);
        roleTypes.add(2);

        QueryWrapper<CrmRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("role_type",roleTypes);
        queryWrapper.eq("is_deleted",0);
        if(DataHelpers.isNotEmpty(queryInfo.getRoleName())){
            queryWrapper.like("role_name", queryInfo.getRoleName());
        }
        return super.page(page, queryWrapper);
    }
}
